package taglibSysMotel;

import java.io.IOException;
import java.util.List;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

import pessoal.cliente.ClienteFiel;

import util.ErroAcessoRepositorioException;
import fachada.Fachada;
import funcional.reserva.ReservaSuite;

public class TagListarReservas extends TagSupport {
	private static final String RESERVAS_OPEN_XML_TAG = "<reservas>";
	private static final String RESERVAS_CLOSE_XML_TAG = "</reservas>";
	private static final String RESERVA_OPEN_XML_TAG = "<reserva>";
	private static final String RESERVA_CLOSE_XML_TAG = "</reserva>";
	private static final String SUITE_OPEN_XML_TAG = "<suite>";
	private static final String SUITE_CLOSE_XML_TAG = "</suite>";
	private static final String FUNCIONARIO_OPEN_XML_TAG = "<funcionario>";
	private static final String FUNCIONARIO_CLOSE_XML_TAG = "</funcionario>";
	private static final String CLIENTE_OPEN_XML_TAG = "<cliente>";
	private static final String CLIENTE_CLOSE_XML_TAG = "</cliente>";
	
	@Override
	public int doStartTag() throws JspException {
		try {
			List<ReservaSuite> reservas = Fachada.obterInstancia().listarReservas();
			JspWriter out = pageContext.getOut();
			out.write(RESERVAS_OPEN_XML_TAG);
			for (ReservaSuite r : reservas ){
				out.write(buildReservaTag(r.getSuite().getNumeroSuite(),
						r.getFuncionario().getCpf(),
						r.getCliente().getCpf()));
			} 
			out.write(RESERVAS_CLOSE_XML_TAG);
			out.close();
		}catch (IOException ex) {
			throw new JspTagException
                  ("Fatal error: hello tag could not write to JSP out");
		}
		return super.doStartTag();
	}

	private String buildReservaTag(int numeroSuite, String cpfFuncionario, String cpfCliente){
		return RESERVA_OPEN_XML_TAG+
		buildSuiteTag(numeroSuite)+
		buildFuncionarioTag(cpfFuncionario)+
		buildClienteTag(cpfCliente)+
		RESERVA_CLOSE_XML_TAG;
	}

	private String buildClienteTag(String cpfCliente) {
		return CLIENTE_OPEN_XML_TAG+cpfCliente+CLIENTE_CLOSE_XML_TAG;
	}

	private String buildFuncionarioTag(String cpfFuncionario) {
		return FUNCIONARIO_OPEN_XML_TAG+cpfFuncionario+FUNCIONARIO_CLOSE_XML_TAG;
	}

	private String buildSuiteTag(int numeroSuite) {
		return SUITE_OPEN_XML_TAG+numeroSuite+SUITE_CLOSE_XML_TAG;
	}
}
